package com.wchen.game.client.handle;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: wchen
 * @Description:
 * @Date: Created in 2019-04-24 16:42
 * Copyright 本内容仅限于杭州阿拉丁信息科技股份有限公司内部传阅，禁止外泄以及用于其他的商业目的
 */
public class DoLoginHandle extends ChannelInboundHandlerAdapter {
    private final static Logger LOGGER = LoggerFactory.getLogger(DoLoginHandle.class);
    private volatile AtomicInteger requestNum = new AtomicInteger(0);
    private final static int MAX_REQ_NUM = 30;
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        LOGGER.info("DoLoginHandle 激活链接 ...");
        String request = "hi, server!";
        ByteBuf byteBuf = Unpooled.copiedBuffer(request.getBytes());
        ctx.writeAndFlush(byteBuf);
        LOGGER.info("写入请求：" + request);
        super.channelActive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        LOGGER.info("DoLoginHandle 开始读取响应 ...");
        ByteBuf byteBuf = (ByteBuf) msg;
        byte[] readBytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(readBytes);
        LOGGER.info("服务端响应： " + new String(readBytes));
        String request = "MMM<MMMMMMMMMMMMMMMMMM";
        Thread.sleep(1000);
        int reqNum = requestNum.addAndGet(1);
        LOGGER.info("再次请求服务端： " + reqNum + request);
        if(reqNum > MAX_REQ_NUM){
            return;
        }
        ctx.writeAndFlush(Unpooled.copiedBuffer(request.getBytes()));
        super.channelRead(ctx, msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        LOGGER.info("DoLoginHandle 出现异常 ...");
        super.exceptionCaught(ctx, cause);
    }
}
